<template>
    <div class="custom-toolbox">
        <!-- 功能条放在前面：展开时从图标左侧滑出 -->
        <div class="toolbox-bar" :class="{ expanded: isExpanded }" :style="{ transform: `scaleX(${scale})` }">
            <!-- 优先实现：作业点位，点击打开/关闭左侧列表 -->
            <button class="tool-btn" @click="onClickJobSite">作业点位</button>
            <!-- 其他按钮暂留为占位，点击先打印日志 -->
            <button class="tool-btn" @click="noop('电子围栏')">电子围栏</button>
            <button class="tool-btn" @click="noop('测量')">测量</button>
            <button class="tool-btn" @click="noop('统计')">统计</button>
            <button class="tool-btn" @click="noop('三维模型')">三维模型</button>
            <button class="tool-btn" @click="noop('路径规划、漫游')">路径规划、漫游</button>
            <button class="tool-btn" @click="noop('卷帘对比')">卷帘对比</button>
            <button class="tool-btn" @click="noop('点位聚合')">点位聚合</button>
            <button class="tool-btn" @click="noop('淹没分析')">淹没分析</button>
            <button class="tool-btn" @click="noop('数据缓存')">数据缓存</button>
            <button class="tool-btn" @click="noop('离线数据')">离线数据</button>
            <button class="tool-btn" @click="noop('地形加载')">地形加载</button>
        </div>

        <!-- 图标始终固定在右侧 -->
        <div class="toolbox-icon" @click="debouncedToggleToolbar">
            <div class="icon-wrapper">
                <mars-icon icon="tool" :width="20"></mars-icon>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue"
import { useWidget } from "@mars/common/store/widget"

const isExpanded = ref(false)
const scale = ref(0)
const animating = ref(false)

// 防抖相关变量
let debounceTimer: number | null = null
const debounceTime = 300 // 防抖时间300ms

// 阻尼动画参数
const stiffness = 0.15
const damping = 0.8
let targetScale = 0
let velocity = 0
let animationId: number | null = null

// 防抖函数
const debouncedToggleToolbar = () => {
    if (debounceTimer) {
        clearTimeout(debounceTimer)
    }

    if (animating.value) { return }

    debounceTimer = setTimeout(() => {
        toggleToolbar()
    }, debounceTime) as unknown as number
}

const toggleToolbar = () => {
    isExpanded.value = !isExpanded.value
    targetScale = isExpanded.value ? 1 : 0

    if (animationId) {
        cancelAnimationFrame(animationId)
    }
    startAnimation()
}

const startAnimation = () => {
    if (animating.value) { return }

    animating.value = true
    const animate = () => {
        const force = (targetScale - scale.value) * stiffness
        velocity += force
        velocity *= damping

        // 限制最大速度，防止过冲
        const maxVelocity = 0.05
        velocity = Math.max(Math.min(velocity, maxVelocity), -maxVelocity)

        scale.value += velocity

        // 检查是否接近目标值
        if (Math.abs(targetScale - scale.value) < 0.01 && Math.abs(velocity) < 0.005) {
            scale.value = targetScale
            animating.value = false
            return
        }

        animationId = requestAnimationFrame(animate)
    }

    animationId = requestAnimationFrame(animate)
}

watch(isExpanded, (newVal) => {
    targetScale = newVal ? 1 : 0
})

const { activate, disable, isActivate } = useWidget()

const onClickJobSite = () => {
    // 打开/关闭 左侧"作业点位列表"微件
    if (!isActivate("job-site-list")) {
        activate("job-site-list")
    } else {
        disable("job-site-list")
    }
}

const noop = (name: string) => {
    console.log(`${name} 被点击（预留功能）`)
}

onMounted(() => {
    // 初始状态
    scale.value = 0
})

onUnmounted(() => {
    // 清理动画和定时器
    if (animationId) {
        cancelAnimationFrame(animationId)
    }
    if (debounceTimer) {
        clearTimeout(debounceTimer)
    }
})
</script>

<style scoped>
.custom-toolbox {
    position: absolute;
    right: 20px;
    bottom: 80px;
    display: flex;
    align-items: flex-end;
    z-index: 100;
    transform: translateZ(0);
    /* 启用GPU加速 */
}

.toolbox-icon {
    width: 40px;
    height: 40px;
    background-color: var(--mars-base-bg, #2c3e50);
    color: var(--mars-base-color, #ecf0f1);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    z-index: 2;
    /* 提高层级确保在工具栏上方 */
    border: 1px solid var(--mars-base-border-color, #34495e);
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;
    position: relative;
    /* 确保图标位置固定 */
}

.toolbox-icon:hover {
    transform: scale(1.05);
    background-color: var(--mars-hover-bg, #34495e);
}

.icon-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
}

.toolbox-bar {
    display: flex;
    align-items: center;
    height: 40px;
    background-color: var(--mars-base-bg, #2c3e50);
    color: var(--mars-base-color, #ecf0f1);
    border-radius: 20px;
    border: 1px solid var(--mars-base-border-color, #34495e);
    overflow: hidden;
    padding: 0;
    margin-right: 0;
    transform-origin: right center;
    /* 从右侧展开 */
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    opacity: 0.95;
    position: relative;
    z-index: 1;
    /* 确保工具栏在图标下方 */
    will-change: transform;
    /* 性能优化 */
}

.toolbox-bar.expanded {
    padding: 0 15px;
    margin-right: 10px;
}

.tool-btn {
    color: var(--mars-base-color, #ecf0f1);
    cursor: pointer;
    white-space: nowrap;
    background: transparent;
    border: none;
    padding: 0 8px;
    height: 100%;
    display: flex;
    align-items: center;
    transition: all 0.2s ease;
    font-size: 13px;
    font-weight: 500;
    flex-shrink: 0;
    /* 防止按钮被压缩 */
}

.tool-btn:hover {
    color: var(--mars-active-color, #3498db);
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .custom-toolbox {
        right: 10px;
        bottom: 60px;
    }

    .toolbox-bar {
        height: 36px;
        border-radius: 18px;
    }

    .toolbox-icon {
        width: 36px;
        height: 36px;
    }

    .tool-btn {
        font-size: 12px;
        padding: 0 6px;
    }
}
</style>
